﻿class Filter
	constructor: (@element, options) ->
		@btn = $("##{options.btnFilter}")
		@grid = $("##{options.grid}")

		@init()

	init: ->
		@element.on "keypress", (e) =>
			return if event.which isnt 13 or $(e.target).is "textarea"
			@search()

		@btn.on "click", @search

	serialize: ->
		@element.find(":input").serialize()

	search: =>
		@grid.jGrid("loadData", null, @serialize(), null)

# jQuery plugin

$.fn.extend
    filter: (options) ->
        defaults =
            grid: null
            btnFilter: null

        _isMethod = (typeof options is "string")
        _arguments = Array::slice.call(arguments, 1)

        _result = @
        @each ->
            element = $ @
            obj = element.data "rhd.filter"

            return if (obj? and not _isMethod)

            if (_isMethod)
                _result = obj[options](_arguments...)
            else
                options = $.extend defaults, options
                $(@).data "rhd.filter", new Filter(element, options)
        _result